package org.albino.evinreisi.authentication;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;


public class CastingAuthenticationProvider implements AuthenticationProvider {
	

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		try {
			// Retrieve user details from web service
			System.out.println("auth.getName()        : " + authentication.getName());
			System.out.println("auth.getCredentials() : " + authentication.getCredentials());
			System.out.println("auth.getPrincipal()() : " + authentication.getPrincipal());
			
//			/authenticationWebServiceResponse = webServiceClientAuthenticationManager.login(authentication.getName(), (String)authentication.getCredentials());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BadCredentialsException("User does not exists!");
		}
		
//		if(authenticationWebServiceResponse.getWebServiceResponseType().equals(WebServiceResponseType.SUCCESS)){
			AuthenticationToken authenticationToken = new AuthenticationToken();
			
			return authenticationToken;
//		}else{
//			System.out.println(authenticationWebServiceResponse.getResponseMessage());
//			System.out.println("-------------");
//			throw new BadCredentialsException(authenticationWebServiceResponse.getResponseMessage());
//		}
		
	}


	@Override
	public boolean supports(Class<? extends Object> authenticationClass) {
		if (authenticationClass.isAssignableFrom(UsernamePasswordAuthenticationToken.class)) {
			System.out.println("Casting Authentication Provider supports "+ authenticationClass);
			return true;
		}

		else if (authenticationClass.isAssignableFrom(AuthenticationToken.class)) {
			System.out.println("Casting Authentication Provider supports "+ authenticationClass);
			return true;
		}

		System.out.println("Casting Authentication Provider dos not supports "+ authenticationClass);

		return false;
	}
	
	 public Collection<GrantedAuthority> getAuthorities(Integer access) {
			List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
			
			authList.add(new GrantedAuthorityImpl("ROLE_USER"));
			
			if ( access.compareTo(1) == 0) {
				authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
			}

			return authList;
	  }

}
